import { refreshTokenApi } from '@src/apis/userApi.ts'

const TokenUtil = (() => {
  const key = 'token'

  type Callback = (token: string, key: string) => void

  let onSetCallbacks: Callback[] = []
  let onRemoveCallbacks: Callback[] = []

  return {
    getToken: () => {
      return localStorage.getItem(key)
    },
    setToken: (token: string) => {
      localStorage.setItem(key, token)
      onSetCallbacks.forEach((c) => c(token, key))
    },
    removeToken: () => {
      localStorage.removeItem(key)
    },
    onSetToken: (callback: Callback) => {
      onSetCallbacks.push(callback)

      return () => {
        onSetCallbacks = onSetCallbacks.filter((c) => c !== callback)
      }
    },
    onRemoveToken: (callback: Callback) => {
      onRemoveCallbacks.push(callback)

      return () => {
        onRemoveCallbacks = onRemoveCallbacks.filter((c) => c !== callback)
      }
    },
    parseJwt(token: string) {
      // 将JWT按照.进行分割，取第二部分（payload部分）
      const base64Url = token.split('.')[1]

      // 对base64Url进行解码
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
      const decodedData = decodeURIComponent(
        atob(base64)
          .split('')
          .map((c) => {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
          })
          .join(''),
      )
      const payload = JSON.parse(decodedData)
      return JSON.parse(payload['aud'][0])
    },
    refresh() {
      return refreshTokenApi().then(({ data: newToken }) => {
        this.setToken(newToken)
      })
    },
  }
})()

export default TokenUtil
